import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/common_api.dart';
import 'package:sainbainu/common/apis/content_api.dart';
import 'package:sainbainu/common/apis/group_api.dart';
import 'package:sainbainu/common/apis/user_api.dart';
import 'package:sainbainu/common/enums/resource_type.dart';
import 'package:sainbainu/common/enums/search_type.dart';
import 'package:sainbainu/common/http/exception.dart';
import 'package:sainbainu/common/models/request/resource_request.dart';
import 'package:sainbainu/common/models/response/content_response.dart';
import 'package:sainbainu/common/models/response/group_list_response.dart';
import 'package:sainbainu/common/models/response/user_list_response.dart';
import 'package:sainbainu/common/repositories/common_repository.dart';
import 'package:sainbainu/common/repositories/content_repository.dart';
import 'package:sainbainu/common/repositories/group_repository.dart';
import 'package:sainbainu/common/repositories/user_repository.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/utils/loading.dart';

import 'index.dart';

class GlobalSearchController extends GetxController {
  GlobalSearchController();

  final state = GlobalSearchState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    state.searchInputController = TextEditingController();
    state.searchInputController.addListener(() {
      state.searchText.value = state.searchInputController.text;
    });

    /// 监听输入框聚焦 展示搜索面板页
    state.searchFocusNode = FocusNode();
    state.searchFocusNode.addListener(() {
      if (state.searchFocusNode.hasFocus) {
        // 输入框聚焦 并且从结果页开始 就重新获取历史记录
        if (state.pageType.value == PageType.result) {
          getSearchHistory();
        }
        state.pageType.value = PageType.searching;
      }
    });

    state.refreshController = EasyRefreshController(
      controlFinishLoad: true,
    );
    state.commonRepository = CommonRepository(CommonApi());
    state.contentRepository = ContentRepository(ContentApi());
    state.groupRepository = GroupRepository(GroupApi());
    state.userRepository = UserRepository(UserApi());

    getSearchHistory();
    getSearchHot();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
    state.searchFocusNode.requestFocus();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.searchFocusNode.dispose();
    state.searchInputController.dispose();
    state.refreshController.dispose();
  }

  /// 获取搜索历史
  Future<void> getSearchHistory() async {
    var list = await state.commonRepository.searchHistory();
    state.historyList = list;
    update(['search_history']);
  }

  /// 获取热门搜索
  Future<void> getSearchHot() async {
    var list = await state.commonRepository.searchHot();
    state.hotList = list;
    update(['search_hot']);
  }

  /// 清空搜索框
  void handleClearInput() {
    state.searchText.value = "";
    state.searchInputController.clear();
    // 聚焦输入框
    state.searchFocusNode.requestFocus();
  }

  /// 输入框搜索
  void handleInputSearch(String value) {
    if (value.isEmpty) return;
    if (state.enableHistoryDelete.value) {
      handleHistoryClearToggle();
    }
    state.pageType.value = PageType.result;
    handleSearch();
  }

  /// 点击历史搜索
  void handleHistorySearch(String value) {
    if (state.enableHistoryDelete.value) return;
    if (state.searchFocusNode.hasFocus) {
      state.searchFocusNode.unfocus();
    }
    state.searchInputController.text = value;
    state.pageType.value = PageType.result;
    handleSearch();
  }

  /// 点击热门搜索
  void handleHotSearch(String value) {
    if (state.enableHistoryDelete.value) {
      handleHistoryClearToggle();
    }
    if (state.searchFocusNode.hasFocus) {
      state.searchFocusNode.unfocus();
    }
    state.searchInputController.text = value;
    state.pageType.value = PageType.result;
    handleSearch();
  }

  /// 开启关闭历史记录删除功能
  void handleHistoryClearToggle() {
    state.enableHistoryDelete.value = !state.enableHistoryDelete.value;
  }

  /// 清空历史记录
  void handleClearHistory() async {
    try {
      LoadingUtil.showLoading();
      await state.commonRepository.clearSearchHistory();
      LoadingUtil.dismiss();
      state.historyList = [];
      update(['search_history']);
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    }
  }

  /// 热门搜索换一换
  void handleRefreshHot() async {
    try {
      LoadingUtil.showLoading();
      await getSearchHot();
    } finally {
      LoadingUtil.dismiss();
    }
  }

  /// tabs 切换
  void handleTabChange(int index) {
    state.tabsIndex.value = index;
    handleSearch();
  }

  /// 搜索
  Future handleSearch() async {
    state.fetchLoading.value = true;
    state.pagerRequest.pageNum = 1;
    state.refreshController.resetFooter();
    try {
      await getSearchList(refresh: true);
    } on CustomHttpException catch (e) {
      LoadingUtil.showError(e.message);
    } catch (e) {
      LoadingUtil.showError('出错啦～');
    } finally {
      state.fetchLoading.value = false;
    }
  }

  Future getSearchList({bool refresh = true}) async {
    final SearchType type = state.tabsIndexToType[state.tabsIndex.value];
    var res = await state.commonRepository.search(
      content: state.searchInputController.text,
      type: type,
    );
    int total = 0;
    if (type == SearchType.note) {
      final entity = ContentListResponse.fromJson(res);
      if (refresh) {
        state.noteListResponse.rows = entity.rows;
      } else {
        state.noteListResponse.rows.addAll(entity.rows);
      }
      state.noteListResponse.total = entity.total;
      total = entity.total;
    } else if (type == SearchType.group) {
      final entity = GroupListResponse.fromJson(res);
      if (refresh) {
        state.groupListResponse.rows = entity.rows;
      } else {
        state.groupListResponse.rows.addAll(entity.rows);
      }
      state.groupListResponse.total = entity.total;
      total = entity.total;
    } else if (type == SearchType.user) {
      final entity = UserListResponse.fromJson(res);
      if (refresh) {
        state.userListResponse.rows = entity.rows;
      } else {
        state.userListResponse.rows.addAll(entity.rows);
      }
      state.userListResponse.total = entity.total;
      total = entity.total;
    }
    state.hasMore =
        state.pagerRequest.pageNum * state.pagerRequest.pageSize < total;
    state.pagerRequest.pageNum++;
    update(['search_list']);
  }

  /// 上拉下载
  Future onRichBottom() async {
    try {
      if (state.hasMore) {
        await getSearchList(refresh: false);
      }
      if (!state.hasMore) {
        state.refreshController.finishLoad(IndicatorResult.noMore);
      } else {
        state.refreshController.finishLoad(IndicatorResult.success);
      }
    } catch (e) {
      state.refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  /// 用户详情页
  toUserDetailPage(int? customerId) {
    if (customerId == null) return;
    Get.toNamed(AppRoutes.userDetail, arguments: {'customerId': customerId});
  }

  /// 小组详情页
  toGroupDetailPage(int? groupId, String? uniqueTag, String? cover) {
    if (groupId == null) return;
    Get.toNamed(
      AppRoutes.groupDetail,
      arguments: {
        'groupId': groupId,
        'uniqueTag': uniqueTag,
        'cover': cover,
      },
    );
  }

  /// 内容详情页
  toContentDetailPage(ContentResponse item) {
    Get.toNamed(
      AppRoutes.contentDetail,
      arguments: {
        'noteId': item.noteId,
        'uniqueTag': item.uniqueTag,
        'avatar': item.avatar,
      },
    );
  }

  /// 点赞、取消点赞
  void onGiveHandle(bool isGive, int? noteId) {
    if (noteId == null) {
      return LoadingUtil.showError('无法点赞');
    }
    var resourceRequest =
        ResourceRequest(resourceType: ResourceType.content, resourceId: noteId);
    if (isGive) {
      state.contentRepository.giveAdd(resourceRequest);
    } else {
      state.contentRepository.giveCancel(resourceRequest);
    }
  }

  /// 收藏、取消收藏
  void onCollectionHandle(bool isGive, int? noteId) {
    if (noteId == null) {
      return LoadingUtil.showError('无法收藏');
    }
    var resourceRequest =
        ResourceRequest(resourceType: ResourceType.content, resourceId: noteId);
    if (isGive) {
      state.contentRepository.collectionAdd(resourceRequest);
    } else {
      state.contentRepository.collectionCancel(resourceRequest);
    }
  }

  /// 加入、取消加入
  void handleJoin(int index) {
    final item = state.groupListResponse.rows[index];
    if (item.groupId == null) {
      return LoadingUtil.showError('无法操作');
    }
    if (item.joinFlag == 1) {
      state.groupRepository.unjoin(item.groupId!);
      state.groupListResponse.rows[index].joinFlag = 0;
    } else {
      state.groupRepository.join(item.groupId!);
      state.groupListResponse.rows[index].joinFlag = 1;
    }
    update(['join_btn']);
  }

  /// 关注、取消关注
  void handleFollow(int index) {
    final item = state.userListResponse.rows[index];
    if (item.customerId == null) {
      return LoadingUtil.showError('无法操作');
    }
    if (item.followFlag == 1) {
      state.userRepository.unFollow(item.customerId!);
      state.userListResponse.rows[index].followFlag = 0;
    } else {
      state.userRepository.follow(item.customerId!);
      state.userListResponse.rows[index].followFlag = 1;
    }
    update(['follow_btn']);
  }
}
